﻿using System;
using System.Data.SqlClient;

namespace Blog
{
	public class BlogException : Exception
	{
		public BlogException(string message)
			: this(message, 0, null, string.Empty)
		{
		}

		public BlogException(string message, int code)
			: this(message, code, null, string.Empty)
		{
		}

		public BlogException(string message, int code, Exception innerException)
			: this(message, code, innerException, string.Empty)
		{ 
		}

		public BlogException(string message, Exception innerException)
			: this(message, 0, innerException, string.Empty)
		{
		}

		public BlogException(string message, int code, string information)
			: this(message, code, null, information)
		{
		}

		public BlogException(string message, string information)
			: this(message, 0, null, information)
		{
		}

		public BlogException(BlogException ucgException)
			: this(ucgException.Message, ucgException.Code, ucgException.InnerException, ucgException.Information)
		{
		}

		public BlogException(Exception exception)
			: this(exception.Message, 0, exception, exception.StackTrace)
		{
		}

		public BlogException(string message, int code, Exception innerException, string information)
			: base(message, innerException)
		{
			Code = code;
			Information = information;
		}

		public string Information
		{
			get;
			private set;
		}

		public int Code
		{
			get;
			private set;
		}

		public override string ToString()
		{
			return Message;
		}

		public BlogException ReThrowException()
		{
			if (this.InnerException is SqlException)
			{
				SqlException sql = (SqlException)this.InnerException;
				this.Code = sql.Number;

				if (sql.Number != 0 && sql.Class >= 20)
				{
					//Unknown server name
					if (sql.Number == 53)
						throw new ServerNotFoundException(this);
					
					//Communication Link Failure
					else
						throw new GeneralNetworkException(this);
				}

				switch (sql.Number)
				{
					/* Client Timeout */
					case -2 :	
					case 1222:	
					case 8645:	throw new TimeOutException(this);

					/* Out of Memory */
					case 701:	throw new OutOfMemoryException(this);

					/* Deadlock Victim */
					case 1204:	
					case 1205:	throw new DeadLockException(this);

					/* No permissions */
					case 229:   throw new UnknownPermissionException(this);

					/* general network error */
					case 64: 
					case 4060: 
					case 10054: 
					case 17142:
					case 1231: throw new GeneralNetworkException(this);

					/* Login failed */
					case 18456: throw new AccessDeniedException(this);
				}
			}

			return this;
		}
	}
}
